package org.lex.utils.collections;

import java.util.Iterator;

import org.lex.filter.Filter;
import org.lex.filter.Filters;


/*
 * immuteable 
 */
public class FilterIterator<T> implements Iterator<T> {
	private Iterator<T> iter = null;
	private Filter<T> filter = Filters.acceptAllFilter();
	private T cachedNext = null;

	public FilterIterator(Iterator<T> iter, Filter<T> filter) {
		if (null == iter)
			throw new NullPointerException("iterator could not be null");
		this.iter = iter;
		if (null == filter)
			filter = Filters.acceptAllFilter();
		this.filter = filter;
	}

	public Filter<T> getFilter() {
		return filter;
	}

	public boolean hasNext() {
		if (null != cachedNext)
			return true;
		while (iter.hasNext()) {
			this.cachedNext = iter.next();
			if (true == filter.accept(this.cachedNext))
				return true;
		}
		this.cachedNext = null;
		return false;
	}

	public T next() {
		T n = this.cachedNext;
		this.cachedNext = null;
		return n;
	}

	public void remove() {
		iter.remove();
	}
}
